﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using IDAL;

namespace DAL
{
    public class SqlgoodsDAL : IgoodsDAL
    {
        GameGOEntities db = DbContextFactory.CreateDbContext();

        public IEnumerable<goods> GetGoodsByName(string name)
        {
            var goodlist = db.goods.Where(o => o.goodName.Contains(name) && o.nowState == 1).OrderBy(s => Guid.NewGuid());
            return goodlist;
        }

        IEnumerable<goods> IgoodsDAL.GetGoodsByRandom(int sum)
        {
            var goodlist = db.goods.Where(o => o.nowState == 1).OrderBy(s => Guid.NewGuid()).Take(sum);
            return goodlist;
        }

        IEnumerable<goods> IgoodsDAL.GetGoodsByType(int type, int sum = 10, string name = "undefined",int orderType = 0)
        {
            IEnumerable<goods> list;
            if (type == 0)
            {
                if (name == "undefined") return db.goods.OrderBy(o => o.ID);
                else list = db.goods.Where(a => a.goodName.Contains(name) && a.nowState == 1).OrderBy(o => o.ID);
            }
            else if (type != -1)
            {
                if (name == "undefined")  list = db.goods.Where(o => o.typeid == type && o.nowState == 1).OrderBy(o => o.ID);
                else list = db.goods.Where(o => o.typeid == type && o.goodName.Contains(name) && o.nowState == 1).OrderBy(o => o.ID);
            }
            else list = db.goods.Where(o => o.typeid == type && o.nowState == 1).Take(sum);

            if(orderType == 1) list = list.OrderBy(o => o.goodprice);
            else if(orderType == 2) list = list.OrderByDescending(o => o.goodprice);
            return list;
        }
        goods IgoodsDAL.GetGoodsByID(int? id) {
            return db.goods.Where(a => a.ID == id && a.nowState == 1).FirstOrDefault();
        }

        IEnumerable<goods> IgoodsDAL.GetAllGoods()
        {
            return db.goods;
        }

        public void ModifyState(int id)
        {
            var ss = db.goods.Where(o => o.ID == id).FirstOrDefault();
            if (ss != null)
            {
                if(ss.nowState == 1)
                {
                    ss.nowState = 2;
                }
                else
                {
                    ss.nowState = 1;
                }
                db.SaveChanges();
            }
        }

        public IEnumerable<goodType> GetTypeList()
        {
            return db.goodType;
        }

        public void Add(goods good)
        {
            db.goods.Add(good);
            db.SaveChanges();
        }

        public void AddGoodsComment(goodComment com)
        {
            db.goodComment.Add(com);
            var order = db.orderDetail.Where(o => o.ID == com.oDId).FirstOrDefault();
            order.nowState = 1;
            db.SaveChanges();
        }
    }
}
